--[[
FilePath: \Lua\View\UIActivityFree\UIActivityFree.lua
0元购活动
--]]

require 'View/UIBase/UIBase'

UIActivityFree = UIBase.New(PanelNames.UIActivityFree)
local _M = UIActivityFree

_M.hasInit = false;
_M.contentItems = nil;
_M.rewardItemCfg = nil;
_M.challengeCountDown = 0;
_M.listIndex = 0;
_M.rewardItemNum = 1;

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnClose);
        self.btnHelp = self:GetChild("help");
        self.title = self:GetChild("title"):GetChild("title");
        self.itemReward = self:GetChild("List");
        self.btnBefore = self:GetChild("before");
        self.btnNext = self:GetChild("next");
        local beforeCtrl = self:GetController("beforeShow");
        beforeCtrl.selectedIndex = 1;
        local nextCtrl = self:GetController("NextShow");
        nextCtrl.selectedIndex = 1;
        self.btnBefore.visible = false;
        self.btnNext.visible = false;
        _M.hasInit = true;

        self:addEvent()
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.updateView);
    self.btnHelp.onClick:Add(self.HelpTip, self);
    self.btnBefore.onClick:Add(self.OnBefore, self);
    self.btnNext.onClick:Add(self.OnNext, self);
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip);
    self.btnBefore.onClick:Remove(self.OnBefore);
    self.btnNext.onClick:Remove(self.OnNext);
end

function _M:HelpTip()
    if self.tableData ~= nil and self.tableData.f_ExplainTitle ~= nil and self.tableData.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.tableData.f_ExplainTitle), tostring(self.tableData.f_ExplainText));
    end
end

function _M:OnBefore()
    self.listIndex = self.listIndex - 1;
    self:ListMoveIndex();
end

function _M:OnNext()
    self.listIndex = self.listIndex + 1;
    self:ListMoveIndex();
end

function _M:ListMoveIndex()
    if self.listIndex < 0 then
        return;
    end
    if self.listIndex >= self.rewardItemNum then
        return;
    end
    if self.listIndex == 0 then
        self.btnBefore.visible = false;
    elseif not self.btnBefore.visible then
        self.btnBefore.visible = true;
    end
    if self.listIndex == (self.rewardItemNum - 1) then
        self.btnNext.visible = false;
    elseif not self.btnBefore.visible then
        self.btnNext.visible = true;
    end
    self.itemReward:ScrollToView(self.listIndex);
end

-- 显示
function _M:OnEnable()
    logicMgr.HeroManager.setGetNewHeroShow(true);
    self:Refresh();
end

function _M:updateView()
    self:Refresh();
end

function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
        return;
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil or self.tableData == nil then
            self:OnBack();
            return;
        end
    end
    if self.rewardItemCfg == nil then
        self.rewardItemCfg = {};
        local tabCfg = G.dataTable[self.tableData.f_ItemTableName];
        self.title.text = getLanguage(self.tableData.f_ActivityName);
        local id = tonumber(self.activeId);
        for k, v in pairs(tabCfg) do
            if tonumber(v.f_ActivityId) == id then
                table.insert(self.rewardItemCfg, v);
            end
        end
        table.sort(self.rewardItemCfg, function(a, b)
            return a.f_Order < b.f_Order;
        end)

        self.challengeCountDown = self.serverData.endTime;
        local cfg = G.dataTable["t_activity"][tostring(self.activeId)];
        if cfg ~= nil and cfg.f_ChallengeTime ~= nil and tonumber(cfg.f_ChallengeTime) > 0 then
            self.challengeCountDown = self.serverData.startTime + tonumber(cfg.f_ChallengeTime);
        end
    end
    if self.contentItems == nil then
        self.contentItems = {};
        self.itemReward:RemoveChildrenToPool();
        self.rewardItemNum = #self.rewardItemCfg;
        for i = 1, self.rewardItemNum do
            local item = self.itemReward:AddItemFromPool();
            local rewardCfg = self.rewardItemCfg[i];
            self:CreateTaskItem(i,item,rewardCfg);
            self.contentItems[i]:OnShow(self:getRewardState(rewardCfg.f_ItemId), self.challengeCountDown);
        end
        if self.rewardItemNum <= 1 then
            self.btnBefore.visible = false;
            self.btnNext.visible = false;
        else
            self.btnBefore.visible = false;
            self.btnNext.visible = true;
        end
        self.itemReward:ScrollToView(0);
    else
        for i = 1, self.rewardItemNum do
            self.contentItems[i]:OnShow(self:getRewardState(self.rewardItemCfg[i].f_ItemId), self.challengeCountDown);
        end
    end
end

function _M:getRewardState(itemId)
    -- state = 0-未购买，1-已购买未领取，2-已领取
    local state = self.serverData.itemState[tostring(itemId)];
    if state == nil then
        return 0;
    end
    return state;
end

function _M:CreateTaskItem(index,itemObj, cfg)
    if self.contentItems[index] then
        return;
    end
    local item = self.ActivityFreeRewardItem.New();
    self.contentItems[index] = item;
    item:OnCreate(itemObj,self, cfg);
end

function _M:OnClose()
    logicMgr.HeroManager.setGetNewHeroShow();
    self:OnBack();
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if self.contentItems then
        for key, value in pairs(self.contentItems) do
            value:OnDestroy();
        end
        self.contentItems = nil;
    end
    self.rewardItemCfg = nil;
    self.hasInit = false;
    self.challengeCountDown = 0;
    self.listIndex = 0;
    self.rewardItemNum = 1;
end


-- 任务类
_M.ActivityFreeRewardItem = Class("ActivityFreeRewardItem",UIComponentInterface)
local _M_T = _M.ActivityFreeRewardItem
function _M_T:OnCreate(obj,parent, cfg)
    self.parent = parent;
    self.fguiObj = obj;
    self.itemCfg = cfg;
    self.isGet = false;
    self.countDown = 0;
    self.timeDown = 0;
    self.rewardState = 0;
    self.timerId = nil;
    self.btnClickState = 3;

    self.lihui = obj:GetChild("lihui");
    self.lihui2 = obj:GetChild("lihui2");
    self.itemIcon = obj:GetChild("ItemIocn");
    self.txtTips = obj:GetChild("Tittle2");
    self.btnGet = obj:GetChild("ConfirmBtn");
    self.typeCtrl = obj:GetController("BtnType");
    self.itemList = obj:GetChild("itemList");
    self.spItem = obj:GetChild("SPitem");
    self.buyCtrl = obj:GetController("Type");
    self.txtCost = obj:GetChild("title");

    self.parent:RegisterOnClick(self.btnGet,self.ClickReward,self);

    self.RoleLihui = nil;
    self.drawWrapper = nil;
    self.itemName = "";
    self:initView();
end

function _M_T:initView()
    local spineType = self.itemCfg.f_SkinID[2];
    local f_hero = self.itemCfg.f_SkinID[1];
    local idle = self.itemCfg.f_SkinID[3] or "idle1";
    if spineType and spineType == 1 then
        if f_hero ~= nil then
            local skinCfg = G.dataTable["t_skin"][tostring(f_hero)];
            if skinCfg ~= nil then
                local imageName = logicMgr.HeroManager.GetHeroDrawingPath(skinCfg.f_HeroID, nil, skinCfg.f_SkinID);
                if self.drawWrapper == nil then
                    self.drawWrapper = GoWrapper.New()
                end
                resMgr:LoadModelPrefab(imageName, function(go)
                    if(self.RoleLihui~=nil)then
                        destroyImmediate(self.RoleLihui);
                    end
                    self.RoleLihui = newObject(go);
                    self.RoleLihui.name = imageName;
                    Util.AddAction(self.RoleLihui,idle,true,0.5);
                    self.RoleLihui:AddComponent(TCanvas);
                    self.drawWrapper:SetWrapTarget(self.RoleLihui,false);
                    Util.Lua_SetLocalPositionXYZ(self.RoleLihui.transform,self.itemCfg.f_RankLocation[1],self.itemCfg.f_RankLocation[2],0);
                    Util.Lua_SetLocalScaleXYZ(self.RoleLihui.transform,self.itemCfg.f_Ranksize[1],self.itemCfg.f_Ranksize[2],1);
                    self.lihui:SetNativeObject(self.drawWrapper);
                end)
            end
        end
    elseif spineType and spineType == 2 then
        local list = TablePool.Get()
        string_split(f_hero,"/",list)
        AddUIPackageDepend(PanelResNames.UIActivityFree,"FUI/"..list[1])
        TablePool.Release(list)
        self.lihui2.url ="ui://"..f_hero;
        Util.PlayAction(self.lihui2.wrapTarget, idle, true);
    end
    logicMgr.CostManager.RefreshItemList(self.itemList, self.itemCfg.f_Rewards);
    logicMgr.CostManager.RefreshItemList(self.spItem, self.itemCfg.f_SPRewards);
    self.itemName = logicMgr.ItemManager.GetItemName(self.itemCfg.f_SPRewards[1][1]);
end
-- state = 0-未购买，1-已购买未领取，2-已领取
function _M_T:OnShow(state, time)
    self.isGet = false;
    self.countDown = time;
    self.rewardState = state;
    self.btnClickState = 3;
    self:Refresh()
end

function _M_T:Refresh()
    self:DestroyTimer();
    self.txtTips.text = "";
    local time = HelperFunc.GetServerTime();
    self.itemIcon.visible = false;
    self.txtCost.text = "";
    if self.rewardState == 2 then
        --已领取
        self.typeCtrl.selectedIndex = 3;
        self.btnClickState = 3;
    elseif self.rewardState == 0 and self.countDown > time then
        -- 未购买
        if self.itemCfg.f_PriceType == EnumConst.CostBuyType.RMB then
            self.txtCost.text = "￥" .. self.itemCfg.f_Price;
            self.buyCtrl.selectedIndex = 1;
        elseif self.itemCfg.f_PriceType == EnumConst.CostBuyType.GOLD then
            self.txtCost.text = self.itemCfg.f_Price;
            self.itemIcon.visible = true;
            self.buyCtrl.selectedIndex = 0;
        end

        self.typeCtrl.selectedIndex = 0;
        self.timeDown = self.countDown - time;
        self.txtTips.text = string.format(getLanguage("ActivityTips2300101"), HelperFunc.GetSurpTimeStr(self.timeDown),self.itemName);
        self.timerId = utimer.timeCall(function()
            if self.timeDown < 0 then
                self:Refresh();
            else
                self.txtTips.text = string.format(getLanguage("ActivityTips2300101"), HelperFunc.GetSurpTimeStr(self.timeDown),self.itemName);
                self.timeDown = self.timeDown - 1;
            end
        end,1000,-1);
        self.btnClickState = 1;
    elseif self.rewardState == 0 and self.countDown < time then
        --不可购买
        self.typeCtrl.selectedIndex = 1;
        self.txtTips.text = getLanguage("ActivityTips2300103");
        self.btnClickState = 3;
    elseif self.rewardState == 1 and self.countDown > time then
        --已购买不可领取
        self.typeCtrl.selectedIndex = 1;
        self.timeDown = self.countDown - time;
        self.txtTips.text = string.format(getLanguage("ActivityTips2300102"), HelperFunc.GetSurpTimeStr(self.timeDown), self.itemName);
        self.timerId = utimer.timeCall(function()
            if self.timeDown < 0 then
                self:Refresh();
            else
                self.txtTips.text = string.format(getLanguage("ActivityTips2300102"), HelperFunc.GetSurpTimeStr(self.timeDown), self.itemName);
                self.timeDown = self.timeDown - 1;
            end
        end,1000,-1);
        self.btnClickState = 3;
    elseif self.rewardState == 1 and self.countDown < time then
        --可领取
        self.typeCtrl.selectedIndex = 2;
        self.btnClickState = 2;
    end
end

function _M_T:DestroyTimer()
    if self.timerId ~= nil then
        utimer.remove(self.timerId);
        self.timerId = nil;
    end
end

function _M_T:OnDestroy()
    if self.RoleLihui~=nil then
        destroy(self.RoleLihui);
        self.RoleLihui = nil;
    end
    if self.drawWrapper ~= nil then
        self.drawWrapper:Dispose();
        self.drawWrapper = nil;
    end
    self:DestroyTimer();
end

function _M_T:ClickReward()
    if self.isGet then
        return;
    end
    if self.btnClickState == 1 then
        if self.itemCfg.f_PriceType == EnumConst.CostBuyType.RMB then
            logicMgr.CostManager.BuyCostType(_M.activeId, {self.itemCfg.f_ItemId}, self.itemCfg.f_ProductId, 1, 2, self.itemCfg.f_Price, nil, self);
        elseif self.itemCfg.f_PriceType == EnumConst.CostBuyType.GOLD then
            self.isGet = true;
            if logicMgr.ItemManager.getBagNumByTableID(CurrencyEnum.GOLD) >= tonumber(self.itemCfg.f_Price) then
                local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
                pop.Init(116, function (flag)
                    if flag then
                        ActivityHandler.sendReqBuyByGoldMessage(_M.activeId, 0, { self.itemCfg.f_ItemId });
                    else
                        self.isGet = false;
                    end
                end, self.itemCfg.f_Price);
            else
                self.isGet = false;
                UISysTips.AddMsg(getLanguage("Character_Tips7"));
            end
        end
    elseif self.btnClickState == 2 then
        self.isGet = true;
        ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, tonumber(self.itemCfg.f_ItemId)});
    end
end

return _M;